from django.http import JsonResponse
from admi.models import Useradmin, UserAdminIntroduce
from django.contrib.auth.hashers import check_password




def validate_user(name, password, uuid_str,authority):
    print(authority, '等级')
    try:
        # 根据uuid获取Useradmin实例
        user_admin = Useradmin.objects.get(uuid=uuid_str)
    except Useradmin.DoesNotExist:
        return JsonResponse({'error': '无效 uuid'}, status=404)

    # 获取关联的UserAdminIntroduce实例
    try:
        user_admin_introduce = UserAdminIntroduce.objects.get(user=user_admin)
    except UserAdminIntroduce.DoesNotExist:
        return JsonResponse({'error': '错误不存在'}, status=404)

    # 验证用户名和密码
    if user_admin.name != name or not check_password(password, user_admin_introduce.password):
        return JsonResponse({'error': '密码或账号错误'}, status=403)

    # 验证权限等级是否大于2

    if user_admin_introduce.grade < authority:
        return JsonResponse({'error': '权限不足'}, status=403)

    return None  # 返回None表示验证通过